<template>
  <page-wrap back title="登录方式" stay-still>
    <view class="login-mode">
      <view class="lm-view">
        <view class="login-img">
          <image
            src="https://upload.yl1001.com/upload/images/view?file=he4UhZZUZucudJgB33klb0df0q28,uN6bDP9m3F8m=pPco0E3N7mPw1Iz9ox3.png"
            alt="" srcset="">
        </view>
        <!-- <view class="desc">该功能需要您登录后使用</view> -->
      </view>
      <u-button v-if="!privacyAuthStatus" class="lm-wechat" type="success" @click="handleShowPrivacyTips">
        手机号码快速登录
      </u-button>
      <u-button v-else-if="isAuthSetting" class="lm-wechat" open-type="getPhoneNumber" type="success"
        @getphonenumber="getPhoneNumber" @click="handleInfo">
        <!-- <u-icon name="weixin-fill"></u-icon> -->
        手机号码快速登录
      </u-button>
      <u-button v-else class="lm-wechat" open-type="getUserInfo" @getuserinfo="getUserInfo"
        :loading="getUserInfoLoading" type="success">
        手机号码登录请先授权
      </u-button>

      <view class="lm-other" @click="handleToLogin"> 其他方式登录 </view>
      <!-- <image class="bt-bg" :src="btBg" mode="" /> -->
      <view class="politica">
        <u-checkbox size="44" label-size="24" v-model="privacyAuthStatus">我已阅读并同意</u-checkbox>
        <text class="text-base" @click.stop="clickSevice">《服务协议》</text>和<text class="text-base"
          @click.stop="clickPrivacy">《隐私政策》</text>
      </view>
    </view>
  </page-wrap>
</template>

<script>
import IMEventHandler from "@/utils/im";
import {
  getWxLoginInfo,
  getUnionID,
  bindPhone,
  wxLogin,
  detailPermission,
  bindPerson,
  clickShareLink,
} from "@/api/index";
import ShareMixin from "@/mixins/share";
export default {
  mixins: [ShareMixin],
  data() {
    return {
      navHeight: 0,
      selfName: this.$selfName,
      logo: this.$imgBaseSelf + "logo.png?v=" + getApp().globalData.nowDate,
      helloImg: this.$imgBaseSelf + "login/hello.png",
      btBg: this.$imgBaseSelf + "login/login_bg_bt.png?v=1",
      fromType: "",
      resumeId: "",
      isAuthSetting: false,
      getUserInfoLoading: false,
      isNewUser: false,
      previewId: {},
      returnUrl: "",
      shareTitle: this.$selfName,
      sharePath: "/pages/index/index",
      privacyAuthStatus: false,
    };
  },
  onLoad(options) {
    this.fromType = options && options.type ? options.type : "";
    this.resumeId = options && options.resumeId ? options.resumeId : "";

    this.checkAuthSetting();
    this.previewId = options;
    this.returnUrl = (options && options.returnUrl) || "";
  },
  created() {
    this.navHeight = getApp().globalData.navHeight;
  },
  onShow() {
    if (!wx.getStorageSync("wx-session3rd")) {
      this.login();
    }
  },
  // onShareAppMessage() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },

  // onShareTimeline() {
  //   return {
  //     title: this.$selfName,
  //     path: "/pages/index/index",
  //   };
  // },
  methods: {
    // 检测用户是否授权
    checkAuthSetting() {
      uni.getSetting({
        success: (res) => {
          if (res && res.authSetting && res.authSetting["scope.userInfo"])
            this.isAuthSetting = true;
        },
      });
    },
    getUserInfo(e) {
      if (e.detail.encryptedData) {
        this.login();
      }
    },
    login() {
      const that = this;
      this.getUserInfoLoading = true;
      uni.login({
        success: function (loginRes) {
          if (loginRes.code) {
            uni.setStorageSync("wx-code", loginRes.code);
            let param = {
              code: loginRes.code,
              rawData: "",
              signature: "",
              encryptedData: "",
              iv: "",
            };
            wxLogin(param).then((wxLoginRes) => {
              if (!wxLoginRes) return;
              let data = wxLoginRes.data || wxLoginRes;
              uni.setStorageSync("wx-session3rd", data.session3rd);
              uni.setStorageSync("openid", data.openid);
              //是否获得用户权限
              uni.getSetting({
                success(settingRes) {
                  if (settingRes.authSetting["scope.userInfo"]) {
                    uni.getUserInfo({
                      success(res) {
                        uni.setStorageSync("encryptedData", res.encryptedData);
                        uni.setStorageSync("iv", res.iv);
                        uni.setStorageSync("signature", res.signature);
                        that.isAuthSetting = true;
                        that.getUserInfoLoading = false;
                      },
                    });
                  }
                },
              });
            });
          }
        },
      });
    },
    handleShowPrivacyTips() {
      uni.showToast({
        title: "请先阅读并同意政策协议",
        icon: "none",
      });
    },
    handleInfo() {
      let that = this;
      uni.getUserInfo({
        success(res) {
          uni.setStorageSync("encryptedData", res.encryptedData);
          uni.setStorageSync("iv", res.iv);
          uni.setStorageSync("signature", res.signature);
          that.getSessionKey();
        },
        fail(err) {
          uni.showToast({ icon: "none", title: "取消登录" });
          // uni.reLaunch({ url: "/pages/index/index" });
        },
      });
    },
    getPhoneNumber(e) {
      if (!e.detail.encryptedData) {
        uni.showToast({ icon: "none", title: "取消登录" });
        // uni.reLaunch({ url: "/pages/index/index" });
      } else {
        this.handleBindPhone(e.detail);
      }
    },
    getSessionKey() {
      let param = {
        session3rd: uni.getStorageSync("wx-session3rd"),
      };
      getWxLoginInfo(param).then((res) => {
        let data = res.data || res;
        if (data && data.indexOf("@@@")) {
          this.getUId(data.split("@@@")[1]);
        }
      });
    },
    getUId(sessionKey) {
      // let param = {
      //   sessionKey: sessionKey,
      //   userInfo: JSON.stringify({
      //     encryptedData: uni.getStorageSync("encryptedData"),
      //     iv: uni.getStorageSync("iv"),
      //     signature: uni.getStorageSync("signature"),
      //   }),
      // };
      let param = {
        sessionKey: sessionKey,
        encryptedData: uni.getStorageSync("encryptedData"),
        iv: uni.getStorageSync("iv"),
      };
      getUnionID(param).then((res) => {
        wx.setStorageSync("wx-unionId", res.unionId);
      });
    },
    handleBindPhone(data) {
      let param = {
        mobileEncrypted: data.encryptedData,
        mobileIv: data.iv,
        spEncrypted: uni.getStorageSync("encryptedData"),
        spIv: uni.getStorageSync("iv"),
        session3rd: uni.getStorageSync("wx-session3rd"),
      };
      uni.showLoading({
        title: "正在登录",
        mask: true,
      });
      bindPhone(param)
        .then((res) => {
          // if (res && res.code == 200) {
          //   this.isNewUser = true;
          // }
          if (res.data && res.data.info && res.data.info.newRegister) {
            this.isNewUser = true;
          }
          if (res.status === "OK") {
            this.handleLogin(res.data.info.personId);

            if (this.isNewUser) {
              this.reportShareData(res.data.info.personId, "reg");
            } else {
              this.reportShareData(res.data.info.personId, "login");
            }
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.status_desc || "手机绑定异常",
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            icon: "none",
            title: err.toString() || "手机绑定异常",
          });
        });
    },
    handleLogin(personId) {
      uni.setStorageSync("person-id", "id" + personId);
      this.bindOpenId(personId);
      let isImLogin =
        getApp().globalData.tim && getApp().globalData.tim.getLoginUser();
      let isLogin = false;
      if (!isImLogin) {
        new IMEventHandler(() => {
          let currentPage = getCurrentPages()[0].route;
          if (currentPage.indexOf("loginMode") >= 0) {
            isLogin = true;
            uni.hideLoading();
            uni.showToast({ icon: "none", title: "登录成功" });
            this.handleJump(personId);
          }
        });
        setTimeout(() => {
          if (!isLogin) {
            getApp().globalData.tim && getApp().globalData.tim.logout();
            getApp().globalData.tim = null;
            uni.hideLoading();
            uni.showToast({ icon: "none", title: "登录成功" });
            this.handleJump(personId);
          }
        }, 5000);
      } else {
        uni.hideLoading();
        uni.showToast({ icon: "none", title: "登录成功" });
        this.handleJump(personId);
      }
    },
    handleToLogin() {
      let path = this.doubleDecodeURIComponent(this.returnUrl);
      if (
        path == "/pagesSub/careerNew/positionDictionary/JobDescriptionDetail"
      ) {
        uni.redirectTo({
          url: `/pagesSub/public/login/index?type=${this.fromType}&resumeId=${this.resumeId}&returnUrl=${this.returnUrl}`,
        });
      } else {
        if (this.previewId.mpaActivityId) {
          uni.navigateTo({
            url: `/pagesSub/public/login/index?type=${this.fromType}&resumeId=${this.resumeId}&mpaActivityId=${this.previewId.mpaActivityId}&sharePersonId=${this.previewId.sharePersonId}`,
          });
        } else {
          uni.navigateTo({
            url: `/pagesSub/public/login/index?type=${this.fromType}&resumeId=${this.resumeId}&returnUrl=${this.returnUrl}`,
          });
        }
      }
    },
    jumpToApply() {
      if (uni.getStorageSync("person-id").slice(2)) {
        // 请求用户数据
        this.$bus.$emit("getUserInfo", (callback) => {
          this.doApply();
        });
      } else {
        this.doApply();
      }
    },
    doApply() {
      const tel = getApp().globalData.userInfo.shouji
        ? getApp().globalData.userInfo.shouji
        : "";
      const enUrl = encodeURIComponent(
        `https://m.job1001.com/v2/apply/#/apply/basic?tel=${tel}`
      );
      uni.navigateTo({
        url: `/pagesSub/userCenter/hrApply/index?url=${enUrl}`,
      });
    },
    jumpToDetail(personId) {
      // 是否内部员工（权限控制资料详情页的查看）
      const userInfo = getApp().globalData.userInfo || { shouji: "" };
      const params = {
        tel: userInfo.shouji,
        personId: personId,
      };
      detailPermission(params).then((res) => {
        if (res.data.isShowDetail == 1) {
          uni.reLaunch({
            url: `/pagesSub/userCenter/hrDetail/index?resumeId=${this.resumeId}`,
          });
        } else {
          if (getApp().globalData.loginStatus === "company") {
            uni.reLaunch({ url: "/pages/companyCenter/index" });
          } else {
            uni.reLaunch({ url: "/pages/userCenter/index" });
          }
        }
      });
    },
    handleJump(personId) {
      setTimeout(() => {
        // 应聘者面试填写
        if (this.fromType == "apply") {
          this.jumpToApply();
          return false;
        }
        // 点击转发详情页，授权后跳转回去
        if (this.resumeId) {
          this.jumpToDetail(personId);
          return false;
        }
        if (
          uni.getStorageSync("routPage") == "pages/reportPreview/reportPreview"
        ) {
          uni.reLaunch({
            url: `/pagesSub/careerGrow/reportPreview/reportPreview?mpaActivityId=${this.previewId.mpaActivityId}&sharePersonId=${this.previewId.sharePersonId}`,
          });
          return;
        }
        let fromLoginStatus = uni.getStorageSync("fromLoginStatus");
        if (fromLoginStatus == "company") {
          getApp().globalData.tabBarList = getApp().globalData["companyTabs"];
          getApp().globalData.loginStatus = "company";
          uni.setStorageSync("login-status", "company");
        }
        let path = this.doubleDecodeURIComponent(this.returnUrl);
        if (
          path == "/pagesSub/careerNew/positionDictionary/JobDescriptionDetail"
        ) {
          uni.redirectTo({ url: path });
          return;
        } else if (path) {
          uni.reLaunch({ url: path });
          return;
        }

        if (this.isNewUser) {
          uni.reLaunch({ url: "/pagesSub/public/identity/index" });
          return;
        }
        if (getApp().globalData.loginStatus === "company") {
          uni.reLaunch({ url: "/pages/companyCenter/index" });
        } else {
          uni.reLaunch({ url: "/pages/userCenter/index" });
        }
      }, 500);
    },

    // 绑定openid
    bindOpenId(personId) {
      const openId = uni.getStorageSync("openid");
      const params = {
        personId: personId,
        openId: openId,
      };
      bindPerson(params);
    },

    reportShareData(personId, type) {
      let shareCode = getApp().globalData.shareCode;
      if (!shareCode) return;

      clickShareLink({
        personId,
        uniqueCode: shareCode,
        type,
      });
    },
    //服务协议
    clickSevice() {
      uni.navigateTo({
        url: `/pagesSub/public/web/BasewebView?url=${encodeURIComponent(
          "https://m5.yl1001.com/marketing/about/agreement.html"
        )}&title=用户服务协议`,
      });
    },
    //隐私政策
    clickPrivacy() {
      uni.navigateTo({
        url: `/pagesSub/public/web/BasewebView?url=${encodeURIComponent(
          "https://m5.yl1001.com/marketing/about/security.html"
        )}`,
      });
    },
    doubleDecodeURIComponent(encodedString) {
      let decodedString = decodeURIComponent(encodedString);
      let encodedCharacters = /%(?:[0-9A-Fa-f]{2})+/g;

      while (encodedCharacters.test(decodedString)) {
        decodedString = decodeURIComponent(decodedString);
      }

      return decodedString;
    },
  },
};
</script>

<style lang="scss">
$img-base-login: $img-base + "login/";
.login-mode {
  flex: 1;
  position: relative;
  background: $uni-bg-color;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 32rpx;
  .lm-view {
    // flex-grow: 1;
    width: 100%;
    margin: 140rpx auto 142rpx;
    .login-img {
      width: 400rpx;
      height: 400rpx;
      margin: 0 auto 53rpx;
      image {
        width: 400rpx;
        height: 400rpx;
      }
    }
    .desc {
      margin: auto;
      text-align: center;
      font-family: PingFangSC-Regular;
      font-size: 32rpx;
      color: #333333;
      text-align: center;
      line-height: 40rpx;
    }
  }
  .lm-wechat {
    width: 460rpx;
    height: 88rpx;
    button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 460rpx;
      height: 88rpx !important;
      font-family: PingFangSC-Regular;
      font-size: 32rpx;
      color: #ffffff;
      text-align: center;
      line-height: 40rpx;
      u-icon {
        margin-right: 16rpx;
        font-size: $uni-font-size-sec;
      }
    }
  }
  .lm-other {
    margin-top: 60rpx;
    color: $u-type-primary;
    font-size: $uni-font-size-lg;
    font-family: PingFangSC-Regular;
    font-size: 32rpx;
    color: #333333;
    text-align: center;
    line-height: 40rpx;
  }
  .politica {
    position: absolute;
    bottom: 100rpx;
    font-size: 24rpx;

    ::v-deep .u-checkbox__label {
      margin-right: 4rpx;
    }
  }
}
</style>
